import { mod360,toPercent } from "./translate"
import { getStyle } from "./style"

// 将组合中的各个子组件拆分出来，并计算它们新的 style
function decomposeComponent (component, editorRect, parentAttr) {
  const componentRect = document.querySelector(`#component${component.id}`).getBoundingClientRect()
  // 获取元素的中心点坐标
  const center = {
    x: componentRect.left - editorRect.left + componentRect.width / 2,
    y: componentRect.top - editorRect.top + componentRect.height / 2,
  }

  component.attr.rotate = mod360(component.attr.rotate + parentAttr.rotate)
  component.attr.width = parseFloat(component.groupAttr.width) / 100 * parentAttr.width
  component.attr.height = parseFloat(component.groupAttr.height) / 100 * parentAttr.height
  // 计算出元素新的 top left 坐标
  component.attr.left = center.x - component.attr.width / 2
  component.attr.top = center.y - component.attr.height / 2
  component.groupAttr = {}
}

function createGroupStyle (groupComponent) {
  const parentAttr = groupComponent.attr
  groupComponent.children.forEach(component => {
    // component.groupAttr 的 top left 是相对于 group 组件的位置
    // 如果已存在 component.groupAttr，说明已经计算过一次了。不需要再次计算
    if (!component.groupAttr || !Object.keys(component.groupAttr).length) {
      const attr = { ...component.attr }
      component.groupAttr = getStyle(attr)
      component.groupAttr.left = toPercent((attr.left - parentAttr.left) / parentAttr.width)
      component.groupAttr.top = toPercent((attr.top - parentAttr.top) / parentAttr.height)
      component.groupAttr.width = toPercent(attr.width / parentAttr.width)
      component.groupAttr.height = toPercent(attr.height / parentAttr.height)
    }
  })
}

export {
  decomposeComponent,
  createGroupStyle
}